package org.windowkit.toolkit;

import java.text.ParseException;
import java.util.regex.Pattern;

import javax.swing.text.DefaultFormatter;

/**
 * This class implements a formatter, for use with JFormattedTextField, with
 * support for regular expressions.
 *
 * @author Eric Lundin
 */
public class RegExFormatter extends DefaultFormatter {

	/**
	 *
	 */
	private static final long serialVersionUID = 5078751931473000088L;
	Pattern pattern;

	public RegExFormatter(final Pattern p) {
		super();
		setPattern(p);
	}

	public RegExFormatter(final String pattern) {
		super();
		setPattern(pattern);
	}

	/**
	 * Set the pattern used by this formatter.
	 *
	 * @param pattern
	 *            The pattern used by this formatter.
	 */
	public void setPattern(final String pattern) {
		this.pattern = Pattern.compile(pattern);
	}

	/**
	 * Set the pattern used by this formatter.
	 *
	 * @param pattern
	 *            The pattern used by this formatter.
	 */
	public void setPattern(final Pattern pattern) {
		this.pattern = pattern;
	}

	/**
	 * Get the pattern used by this formatter.
	 *
	 * @return The pattern currently used by this formatter.
	 */
	public Pattern getPattern() {
		return pattern;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see javax.swing.JFormattedTextField.AbstractFormatter#stringToValue(java.lang.String)
	 */
	@Override
	public Object stringToValue(final String text) throws ParseException {
		Pattern pattern = getPattern();
		if (pattern != null) {
			if (pattern.matcher(text).matches()) {
				return super.stringToValue(text);
			}
			throw new ParseException("Pattern did not match", 0);
		}
		return text;
	}

}
